package de.cube3d.blitwit.render 
{
	import de.cube3d.blitwit.space.SpaceObject;
	import flash.display.BitmapData;
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	
	
	public class BlitSpriteTexture extends SpaceObject
	{
		private var _bm:BitmapData;
		private static var _s:Sprite = new Sprite();
		private static var _m:Matrix = new Matrix(1, 0, 0, 1, 0, 0);
		public var phaseX:Number = 0;
		public var phaseY:Number = 0;
		public function BlitSpriteTexture(bm:BitmapData, x:Number, y:Number, width:Number, height:Number) 
		{
			super(x, y, width, height);
			_bm = bm;
		}
		
		override public function draw(bm:BitmapData, x:Number, y:Number, scale:Number, clipRect:Rectangle):void 
		{
			var xx:Number = Math.max(int(clipRect.x), int(x));
			var yy:Number = Math.max(int(clipRect.y), int(y));
			var x2:Number = Math.min(int(clipRect.x) + int(clipRect.width), int(width) + int(x));
			var y2:Number = Math.min(int(clipRect.y) + int(clipRect.height), int(height)+int(y));
			_s.graphics.clear();
			_m.a = _m.d = scale;
			_m.tx = (int(x/scale) + phaseX) %_bm.width * scale; // modulo the sizes of the tex - if tx / ty is > 0x8000 or 
			_m.ty = (int(y/scale) + phaseY)% _bm.height * scale; // < 0x8000, it won't transform. Quite "funny".
			//trace(_m,y,yy)
			_s.graphics.beginBitmapFill(_bm,_m,true,scale != 1);
			_s.graphics.drawRect(xx, yy, x2-xx, y2-yy);
			_s.graphics.endFill();
			bm.draw(_s);
			//bm.fillRect(new Rectangle(0, 0, 100, 100), 0xff);
		}
		
		override public function getCopy(overwrite:SpaceObject=null):SpaceObject {
			if (overwrite == null) return new BlitSpriteTexture(_bm, x, y, width, height);
			var cp:BlitSpriteTexture = super.getCopy(overwrite) as BlitSpriteTexture;
			cp._bm = _bm;
			cp.phaseX = phaseX;
			cp.phaseY = phaseY;
			return cp;
		}
	}

}